<template>
  <el-container class="searchLayout">
    <!-- 搜索栏 -->
    <el-header class="search">
      <el-select v-model="categoryIndex" placeholder="请选择类别" @change="bindCategoryChange">
        <el-option
          v-for="(category, index) in categories"
          :key="index"
          :label="category"
          :value="index"
        />
      </el-select>
      <el-input
        v-model="keyword"
        placeholder="输入关键词"
        @keyup.enter.native="onSearch"
        clearable
        @clear="onClear"
      >
        <template #append>
          <el-button icon="el-icon-search" @click="onSearch">搜索</el-button>
        </template>
      </el-input>
    </el-header>

    <el-main v-if="!classList.length && !noSearch">
      <el-card v-if="historySearch.length" class="history">
        <div slot="header" class="clearfix">
          <span>最近搜索</span>
          <el-button type="text" class="icon" @click="removeHistory">
            <el-icon><delete /></el-icon>
          </el-button>
        </div>
        <el-tag
          v-for="tab in historySearch"
          :key="tab"
          @click="clickTab(tab)"
          class="tab"
        >
          {{ tab }}
        </el-tag>
      </el-card>

      <el-card class="recommend">
        <div slot="header" class="clearfix">
          <span>热门搜索</span>
        </div>
        <el-tag
          v-for="tab in recommendList"
          :key="tab"
          @click="clickTab(tab)"
          class="tab"
        >
          {{ tab }}
        </el-tag>
      </el-card>
    </el-main>

    <el-main v-if="!noSearch">
  <!-- 如果没有搜索结果 -->
  <el-empty v-if="classList.length === 0" description="暂无搜索结果"></el-empty>

  <!-- 搜索结果列表 -->
  <el-row v-else :gutter="20" class="list">
    <el-col :span="6" v-for="item in classList" :key="item.id">
      <el-card :body-style="{ padding: '0px' }">
        <img v-if="categoryIndex ===1" :src="item.smallPicurl" class="image" @click="goPreviewWall(item.id)" />
        <img v-else-if="categoryIndex ===0" :src="item.imgUrl" class="image" @click="goPreviewAlbum(item.id)" />
      </el-card>
    </el-col>
  </el-row>
  <el-footer class="loadingLayout" v-if="noData || classList.length">
    <el-loading :loading="!noData" text="加载中..."></el-loading>
  </el-footer>
</el-main>
  </el-container>
</template>

<script setup>
import { ref, watch, toRaw } from 'vue';
import { ElMessage, ElLoading } from 'element-plus';
import {listWall} from '@/api/wallpaper/wall.js'
import {listAlbum} from '@/api/wallpaper/album.js'
import { useRouter } from "vue-router";
const router = useRouter();
const keyword = ref('');
// 类别选项
const categories = ['专辑', '壁纸'];
const categoryIndex = ref(0);

// 绑定类别变化事件
const bindCategoryChange = (value) => {
  categoryIndex.value = value;
};

// 根据所选类别调用不同的API
const apiCaller = async (params) => {
  // 根据描述和标题查询
  let query = {...params};
  switch (categoryIndex.value) {
    case 0:
      // 专辑查询
      query = {
        ...query,
        description: keyword.value,
      };
      return await listAlbum(query);
    case 1:
      // 壁纸查询
      query = {
        ...query,
        description: keyword.value,
      };
      return await listWall(query);
    default:
      return { data: { rows: [] } };
  }
};

// 初始化查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 12,
  keyword: '',
});

// 搜索历史词
const historySearch = ref(JSON.parse(localStorage.getItem('historySearch')) || []);

// 热门搜索词
const recommendList = ref(['动漫', '萌宠', '自然', '人物']);

// 没有更多
const noData = ref(false);
// 没有搜索结果
const noSearch = ref(false);

// 搜索结果列表
const classList = ref([]);

// 添加对 classList 的监听
watch(classList, (newVal) => {
  // console.log('classList updated:', JSON.stringify(toRaw(newVal), null, 2));
});

// 处理搜索逻辑
const handleSearch = async () => {
  ElMessage({ message: '加载中...', type: 'info', duration: 0, showClose: true });
    queryParams.value.pageNum = 1;
    classList.value = [];
    noData.value = false;
    noSearch.value = false;

    const res = await apiCaller(queryParams.value);
    console.log("Raw API Response:", res); // 打印原始响应以检查其结构

      classList.value = res.rows
      localStorage.setItem('storgClassList', JSON.stringify(classList.value));
      noData.value = classList.value.length < queryParams.value.pageSize;
      noSearch.value = classList.value.length === 0;

      if (queryParams.value.keyword.trim()) {
        const updatedHistory = [
          queryParams.value.keyword,
          ...historySearch.value.filter((item) => item !== queryParams.value.keyword),
        ].slice(0, 5);

        historySearch.value = updatedHistory;
        // 将搜索的关键词放入缓存
        localStorage.setItem('historySearch', JSON.stringify(updatedHistory));
      }

    ElMessage.closeAll(); // 关闭加载中消息
}



// 点击搜索
const onSearch = () => {
  handleSearch();
}

// 点击清除按钮
const onClear = () => {
  initParams();
}

// 点击标签进行搜索
const clickTab = (value) => {
  initParams(value);
  onSearch();
}

// 点击清空搜索记录
const removeHistory = () => {
  ElMessageBox.confirm('是否清空历史搜索？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    localStorage.removeItem('historySearch');
    historySearch.value = [];
  })
}

// 初始化参数
const initParams = (value = '') => {
  classList.value = [];
  noData.value = false;
  noSearch.value = false;
  queryParams.value = {
    pageNum: 1,
    pageSize: 12,
    keyword: value || '',
  }
}

const goPreviewWall = (id) => {
  router.push(`/preview/wallpaper/${id}`);
};
const goPreviewAlbum = (id) => {
  router.push(`/preview/album/${id}`);
};
const goPreview3 = (id) => {
  // console.log(id, type)
  // router.push(`/preview/album?id=${id}`);
};
</script>

<style lang="scss" scoped>
.searchLayout {
  padding: 20px;
  display: flex;
  flex-direction: column;

  .search {
    display: flex;
    align-items: center;
    background-color: #fff;
    border-radius: 20px;
    overflow: hidden;
    margin-bottom: 20px;

    .el-select {
      flex: 3;
      margin-right: 10px;
    }

    .el-input {
      flex: 7;
    }
  }

  .history,
  .recommend {
    padding: 20px;
    background-color: #fff;
    border-radius: 10px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
  }

  .list {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;

    .el-card {
      width: 250px;
      height: 400px;
      overflow: hidden;
      border-radius: 10px;
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);

      .image {
        width: 200px;
        height: 300px;
        object-fit: cover;
        transition: transform 0.3s ease;
      }

      .image:hover {
        transform: scale(1.05);
      }
    }
  }

  .loadingLayout {
    text-align: center;
    margin-top: 20px;
  }
}

// 添加媒体查询以响应不同屏幕尺寸
@media (max-width: 768px) {
  .searchLayout {
    padding: 10px;

    .search {
      flex-direction: column;
      align-items: stretch;

      .el-select {
        margin-bottom: 10px;
      }
    }

    .list {
      .el-card {
        width: 100%;
        height: auto;
      }
    }
  }
}

@media (max-width: 480px) {
  .searchLayout {
    .list {
      gap: 10px;

      .el-card {
        width: 100%;
        height: auto;
      }
    }
  }
}
</style>
